package com.ocom.mqsimple.business.gzhmsg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.request.simple.GzhMsgRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.HttpUtils;
import com.ocom.common.utils.wx.WxGhUtils;
import com.ocom.mqsimple.config.GzhMsgConfig;
import com.ocom.mqsimple.feign.CompanyClientService;
import com.ocom.mqsimple.feign.HumanClientService;
import com.ocom.mqsimple.feign.PayConfigClientService;
import com.ocom.mqsimple.utils.wechatmsg.TemplateData;
import com.ocom.mqsimple.utils.wechatmsg.WxChatSendUtil;
import com.ocom.mqsimple.utils.wechatmsg.WxSendParam;
import com.ocom.redis.util.RedisUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class GzhMsgConsumerMqListener {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    HumanClientService humanClientService;

    @Autowired
    private CompanyClientService companyClientService;

    private Logger logger = LoggerFactory.getLogger(GzhMsgConsumerMqListener.class);

    @RabbitListener(queues = GzhMsgConfig.GzhMsg_QUEUE)
    public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
//        logger.info("GzhMsgXf message【{}】", message);
        String requestMessage = new String(message.getBody(), StandardCharsets.UTF_8);

        try {

            Object requestRedis = redisUtil.get(requestMessage);

            if (requestRedis == null) {
                logger.info("GzhMsgError:redis为空异常");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }

            GzhMsgRequest gzhMsgRequest = JSON.parseObject(JSON.toJSONString(requestRedis), GzhMsgRequest.class);

            logger.info("GzhMsgXf message【{}】", gzhMsgRequest);

            if (!CommonUtil.isNull(gzhMsgRequest.getOrderNo())) {
                boolean lock2 = redisUtil.lock("gzhMsg:orderNo:" + gzhMsgRequest.getOrderNo(), 180);
                if (!lock2) {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    return;
                }
            }

            String canKey = "wechat_app_info#comId:" + gzhMsgRequest.getComId();
            Object tokenRedis = redisUtil.get(canKey);

            EntityWechatAppInfo entityWechatAppInfo = null;

            String token = null;


            if (tokenRedis == null) {

                //TODO  1 固定本单位  2用指定通道
//                Long merchId = gzhMsgRequest.getMerchId();
//                Result result4 = companyClientService.getCompanyConfig(gzhMsgRequest.getComId(), "gzhOcom");
//                if (result4.getCode() == 200) {
//                    List<EntityCompanyConfig> companyConfigList = JSON.parseArray(JSON.toJSONString(result4.getData()), EntityCompanyConfig.class);
//                    if (companyConfigList != null && companyConfigList.size() > 0
//                            && companyConfigList.get(0).getConfig().equals("true")) {
//                        merchId = 0l;
//                    }
//                }
                Result result1 = payConfigClientService.getWxInfo(gzhMsgRequest.getComId(), 0l);
                if (result1.getCode() != 200) {
                    //返回
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    redisUtil.set(canKey, "null", 3600l);
                    return;
                }
                entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityWechatAppInfo.class);

                if (gzhMsgRequest.getComId() != 668l) {
                    token = WxGhUtils.getAccessToken(entityWechatAppInfo.getAppid(), entityWechatAppInfo.getAppsecret());

                    if (token == null) {
                        logger.error("GzhMsgError token获取异常 【{}】", gzhMsgRequest);
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                        redisUtil.set(canKey, "null", 30l);
                        return;
                    }
                }
                entityWechatAppInfo.setRemark(token);
                redisUtil.set(canKey, entityWechatAppInfo, 7000l);
            } else {
                if (tokenRedis.toString().equals("null")) {
                    logger.error("GzhMsgError token空 【{}】", gzhMsgRequest);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    redisUtil.set(canKey, "null", 30l);
                    return;
                }
                entityWechatAppInfo = (EntityWechatAppInfo) tokenRedis;
                token = entityWechatAppInfo.getRemark();
            }

            if(gzhMsgRequest.getComId() == 668l){
                Map<String, Object> reso = HttpUtils.doGet("https://shgd.lunyu-edu.com/lcapi/scc-open-api/v1/native/getWxTokenByAppIdSecret?appId=wx47714cc06dc601e2&secret=951f1946940aa221679e476740a2cb05&tenantId=583be6b03a484f07b59e6c24c2cf1f2a");
                log.info("获取GZhtoken ,【{}】",reso);
                token = (String)reso.get("data");
            }


            Result result = humanClientService.getWxUserByPid(gzhMsgRequest.getComId(),gzhMsgRequest.getPId(),entityWechatAppInfo.getAppid());
            if (result.getCode() != 200 || result.getData()==null) {
                //返回
                logger.error("GzhMsgError 人员找不到 【{}】", gzhMsgRequest);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            EntityWechatPerInfo entityWechatPerInfo  = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatPerInfo.class);


            JSONObject templateJson = JSON.parseObject(entityWechatAppInfo.getAppPrivateKey());


            String mes = "";
            if (gzhMsgRequest.getType() == 1) {
                WxSendParam wxSendParam = new WxSendParam();
                Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
                orderSendWxSend.put("phrase2", new TemplateData(gzhMsgRequest.getParams().getUserName()));
                orderSendWxSend.put("amount4", new TemplateData(gzhMsgRequest.getParams().getPayMoney()));
                orderSendWxSend.put("time6", new TemplateData(gzhMsgRequest.getParams().getPayTime()));
                orderSendWxSend.put("amount8", new TemplateData(gzhMsgRequest.getParams().getBalance()));
                orderSendWxSend.put("phrase7", new TemplateData(gzhMsgRequest.getParams().getAccTypeName()));
                wxSendParam.setToken(token);
                wxSendParam.setOrderMap(orderSendWxSend);
                wxSendParam.setBusinessOpenId(entityWechatPerInfo.getOpenid());
                wxSendParam.setTemplateId(templateJson.getString("template1"));
                mes = WxChatSendUtil.WxChatSendOrderNotice(wxSendParam);
                log.info("公众号消息 【{}】 【{}】 【{}】 ",gzhMsgRequest,wxSendParam,mes);
            } else if(gzhMsgRequest.getType() == 2) {
                WxSendParam wxSendParam = new WxSendParam();
                Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
                orderSendWxSend.put("thing5", new TemplateData(gzhMsgRequest.getParams().getUserName()));
                orderSendWxSend.put("thing3", new TemplateData(gzhMsgRequest.getParams().getPointName()));
                orderSendWxSend.put("time4", new TemplateData(gzhMsgRequest.getParams().getPayTime()));
                orderSendWxSend.put("amount2", new TemplateData(gzhMsgRequest.getParams().getPayMoney()));
                orderSendWxSend.put("amount6", new TemplateData(gzhMsgRequest.getParams().getBalance()));
                wxSendParam.setToken(token);
                wxSendParam.setOrderMap(orderSendWxSend);
                wxSendParam.setBusinessOpenId(entityWechatPerInfo.getOpenid());
                wxSendParam.setTemplateId(templateJson.getString("template2"));
                mes = WxChatSendUtil.WxChatSendOrderNotice(wxSendParam);
                log.info("公众号消息 【{}】 【{}】 【{}】 ",gzhMsgRequest,wxSendParam,mes);
            } else if(gzhMsgRequest.getType() == 3) {
                WxSendParam wxSendParam = new WxSendParam();
                Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
                orderSendWxSend.put("time1", new TemplateData(gzhMsgRequest.getParams().getPayTime()));
                orderSendWxSend.put("thing2", new TemplateData(gzhMsgRequest.getParams().getUserName()));
                orderSendWxSend.put("thing3", new TemplateData(gzhMsgRequest.getParams().getPointName()));
                wxSendParam.setToken(token);
                if (!CommonUtil.isNull(gzhMsgRequest.getParams().getPic())) {
                    wxSendParam.setUrl(gzhMsgRequest.getParams().getPic());
                }
                wxSendParam.setOrderMap(orderSendWxSend);
                wxSendParam.setBusinessOpenId(entityWechatPerInfo.getOpenid());
                wxSendParam.setTemplateId(templateJson.getString("template3"));
                mes = WxChatSendUtil.WxChatSendOrderNotice(wxSendParam);
                log.info("公众号消息 【{}】 【{}】 【{}】 ",gzhMsgRequest,wxSendParam,mes);
            } else if(gzhMsgRequest.getType() == 4) {
                WxSendParam wxSendParam = new WxSendParam();
                Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
                orderSendWxSend.put("time3", new TemplateData(gzhMsgRequest.getParams().getPayTime()));
                orderSendWxSend.put("thing2", new TemplateData(gzhMsgRequest.getParams().getUserName()));
                orderSendWxSend.put("const6", new TemplateData(gzhMsgRequest.getParams().getStatus()));
                orderSendWxSend.put("thing4", new TemplateData(gzhMsgRequest.getParams().getPointName()));
                wxSendParam.setToken(token);
                if (!CommonUtil.isNull(gzhMsgRequest.getParams().getPic())) {
                    wxSendParam.setUrl(gzhMsgRequest.getParams().getPic());
                }
                wxSendParam.setOrderMap(orderSendWxSend);
                wxSendParam.setBusinessOpenId(entityWechatPerInfo.getOpenid());
                wxSendParam.setTemplateId(templateJson.getString("template4"));
                mes = WxChatSendUtil.WxChatSendOrderNotice(wxSendParam);
                log.info("公众号消息 【{}】 【{}】 【{}】 ",gzhMsgRequest,wxSendParam,mes);
            } else if (gzhMsgRequest.getType() == 5) {
                WxSendParam wxSendParam = new WxSendParam();
                Map<String, TemplateData> orderSendWxSend = new HashMap<>(5);
                orderSendWxSend.put("amount2", new TemplateData(gzhMsgRequest.getParams().getPayMoney()));
                orderSendWxSend.put("thing1", new TemplateData(gzhMsgRequest.getParams().getUserName()));
                orderSendWxSend.put("time3", new TemplateData(gzhMsgRequest.getParams().getPayTime()));
                orderSendWxSend.put("thing4", new TemplateData(gzhMsgRequest.getParams().getItemName()));
                orderSendWxSend.put("character_string10", new TemplateData(gzhMsgRequest.getParams().getOrderNo()));
                wxSendParam.setToken(token);
                wxSendParam.setOrderMap(orderSendWxSend);
                wxSendParam.setBusinessOpenId(entityWechatPerInfo.getOpenid());
                wxSendParam.setTemplateId(templateJson.getString("template5"));
                mes = WxChatSendUtil.WxChatSendOrderNotice(wxSendParam);
                log.info("公众号消息 【{}】 【{}】 【{}】 ",gzhMsgRequest,wxSendParam,mes);
            }

            JSONObject jsonObject =JSON.parseObject(mes);
            if(jsonObject.getInteger("errcode")==40001){
                logger.error("GzhMsgError 移除redis token 【{}】", jsonObject);
                redisUtil.del(canKey);
            }

            //{"errcode":0,"errmsg":"ok","msgid":3610895108259708932}

        } catch (Exception e) {
            logger.info("GzhMsgConsumerMqListener-出现异常队列消息开始进入死信队列{{}}", e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}
